//
//  StoreDetailViewController.m
//  WisdomZhuHai
//
//  Created by Admin on 14-10-28.
//  Copyright (c) 2014年 wyd. All rights reserved.
//

#import "StoreDetailViewController.h"
#import "HotRateView.h"
#import "OrderViewController.h"
#import "UIWebControl.h"

@interface StoreDetailViewController ()

@property (nonatomic,assign) BOOL ifShowAll;
@property (nonatomic,strong) NSString* brief;
@property (nonatomic,strong) NSArray* goodsList;
@property (nonatomic,strong) NSMutableArray* ifGoodsShowDetail;

@end

static const CGFloat PHOTOCELL_HEIGHT = 160;

@implementation StoreDetailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.ifShowAll = NO;
    
    self.tableView.backgroundColor = [Common colorWithRGB:0xdbdcdc];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 16.f)];
    self.tableView.tableFooterView.backgroundColor = self.tableView.backgroundColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self getStoreDetail];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)onClickLocation:(id)sender
{
    NSLog(@"onClickLocation");
}

#pragma mark - Protocol request
- (void)getStoreDetail
{
    [[ProtocolManager shareInstance] getStoreDetail:self.storeId sendType:nil target:self selector:@selector(getStoreDetailCallback:)];
}

#pragma mark - Protocol call back
- (void)getStoreDetailCallback:(NSDictionary*)dic
{
    NSLog(@"getStoreDetailCallback %@", dic);
    if (dic == nil) {
        return;
    }
    self.dataDic = dic;
    id list = [Common valueForKey:P_LIST dic:dic];
    if ([list isKindOfClass:[NSArray class]]) {
        self.goodsList = list;
        self.ifGoodsShowDetail = [NSMutableArray array];
        for (int i=0; i<self.goodsList.count; i++) {
            [self.ifGoodsShowDetail addObject:[NSNumber numberWithBool:NO]];
        }
    }
    self.brief = [Common valueForKey:P_SMALL_INTRO dic:dic];
    [self.tableView reloadData];
}

#pragma mark - Private
- (void)loadStoreTitleCellData:(UITableViewCell*)cell
{
    NSString *name = [Common valueForKey:P_NAME dic:self.dataDic];
    CGFloat star = [[Common valueForKey:P_STAR dic:self.dataDic] floatValue];
    NSString *location = [Common valueForKey:P_LOCATION dic:self.dataDic];
    
    UILabel *lbName = (UILabel*)[cell viewWithTag:1001];
    lbName.text = name;
    
    UIButton *btnLocation = (UIButton*)[cell viewWithTag:1002];
    [btnLocation addTarget:self action:@selector(onClickLocation:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *lbAddress = (UILabel*)[cell viewWithTag:1005];
    lbAddress.text = [NSString stringWithFormat:@"位置：%@", location];
    
    UIView *starView = [cell viewWithTag:1004];
    for (UIView* view in starView.subviews) {
        [view removeFromSuperview];
    }
    HotRateView *hotView = [[HotRateView alloc] initWithHotRate:star];
    CGRect frame = hotView.frame;
    frame.origin.x = 0;
    frame.origin.y = (starView.bounds.size.height - hotView.bounds.size.height)/2;
    hotView.frame = frame;
    [starView addSubview:hotView];
}

- (NSArray*)getGoodsDetail:(int)index
{
    if (index >= self.goodsList.count) {
        return nil;
    }
    NSDictionary* dic = self.goodsList[index];
    NSMutableArray *details = [NSMutableArray array];
    
    NSDictionary* detailAttribute = @{P_PRICE:@"价格", P_AREA_SQUARE:@"房间面积", P_FLOOR:@"楼层",P_HAVE_BREAKFAST:@"早餐",P_SCHEDULE:@"班期",P_SET_OUT:@"出发地点"};
    NSDictionary* detailUnit = @{P_PRICE:@"元", P_AREA_SQUARE:@"㎡", P_FLOOR:@"楼"};
    
    for (NSString *key in [dic allKeys]) {
        id obj = dic[key];
        NSString *detail = nil;
        if ([obj isEqualToString:@""]) {
            continue;
        }
        if ([key isEqualToString:P_HAVE_BREAKFAST]) {
            if ([obj intValue] == 0) {
                detail = [NSString stringWithFormat:@"%@：%@", @"早餐", @"无"];
                //obj = @"无";
            }
            else {
                detail = [NSString stringWithFormat:@"%@：%@", @"早餐", @"有"];
                //obj = @"有";
            }
        }
        else {
            NSString *attribute = detailAttribute[key];
            if (attribute == nil)
                continue;
            NSString *unit = detailUnit[key];
            unit = (unit == nil)?@"":unit;
            if (obj == nil)
                continue;
            detail = [NSString stringWithFormat:@"%@：%@%@", attribute, obj, unit];
        }
        
        [details addObject:detail];
    }
    
    return details;
}

#pragma mark - StoreBriefCellDelegate
//点击更多 /*modify by Ryan*/
- (void)onClickShowAll:(UITableViewCell *)cell
{
//    self.ifShowAll = !self.ifShowAll;
//    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationAutomatic];
    NSLog(@"onClickMore");
    NSString *path = [Common valueForKey:P_DETAIL_LINK dic:self.dataDic];
        WebIOS *webCtrl = [[WebIOS alloc] initWithFrame:self.view.bounds url:[NSURL URLWithString:[[ProtocolManager shareInstance].server_url stringByAppendingString:path]]];
    [self.navigationController pushViewController:webCtrl animated:YES];
}

//点击进入官网 /*modify by Ryan*/
- (void)onClickHomePage:(UITableViewCell *)cell
{
    NSLog(@"onClickHomePage");
    NSString *path = [Common valueForKey:P_HOME_PAGE dic:self.dataDic];
    if ([path isEqualToString:@""]) {
        return;
    }
    WebIOS *webCtrl = [[WebIOS alloc] initWithFrame:self.view.bounds url:[NSURL URLWithString:path]];
    [self.navigationController pushViewController:webCtrl animated:YES];
}

#pragma mark - GoodsCellDelegate
- (void)showGoodsDetail:(UITableViewCell*)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath == nil) {
        return;
    }
    if (indexPath.row < self.ifGoodsShowDetail.count) {
        self.ifGoodsShowDetail[indexPath.row] = [NSNumber numberWithBool:![self.ifGoodsShowDetail[indexPath.row] boolValue]];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void)bookGoods:(UITableViewCell*)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath == nil) {
        return;
    }
    if (indexPath.row < self.goodsList.count) {
        OrderViewController *orderViewCtrl = [[OrderViewController alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        orderViewCtrl.storeId = self.storeId;
        orderViewCtrl.storeInfo = self.dataDic;
        orderViewCtrl.goodsInfo = self.goodsList[indexPath.row];
        [self.navigationController pushViewController:orderViewCtrl animated:YES];
    }
}

- (void)onClickLink:(UITableViewCell*)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath == nil) {
        return;
    }
    if (indexPath.row < self.goodsList.count) {
        NSDictionary *dic = self.goodsList[indexPath.row];
        NSString *path = [Common valueForKey:P_DETAIL_LINK dic:dic];
        NSURL *url = [NSURL URLWithString:[[ProtocolManager shareInstance].server_url stringByAppendingString:path]];
        WebIOS *webCtrl = [[WebIOS alloc] initWithFrame:self.view.bounds url:url];
        [self.navigationController pushViewController:webCtrl animated:YES];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    if (self.dataDic == nil) {
        return 0;
    }
    if (self.goodsList.count == 0) {
        return 3;
    }
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 3) {
        return self.goodsList.count;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1 || section == 3)
        return 8;
    return 0;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = self.tableView.backgroundColor;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            return PHOTOCELL_HEIGHT;
        case 1:
            return STORE_TITLE_CELL_HEIGHT;
        case 2:
        {
            return [StoreBriefCell getCellHeight:self.brief ifShowAll:self.ifShowAll];
        }
        case 3:
        {
            if (indexPath.row >= self.goodsList.count) {
                return 0;
            }
            BOOL ifShowDetail = [self.ifGoodsShowDetail[indexPath.row] boolValue];
            return [GoodsCell getCellHeight:[self getGoodsDetail:indexPath.row] ifShowDetail:ifShowDetail];
        }
        default:
            return 0;
    };
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    // Configure the cell...
    switch (indexPath.section) {
        case 0:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"PhotoCell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PhotoCell"];
                UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.contentView.bounds.size.width, PHOTOCELL_HEIGHT)];
                [cell.contentView addSubview:imgView];
                imgView.tag = 1000;
            }
            UIImageView *imgView = (UIImageView*)[cell viewWithTag:1000];
            NSString* imgPath = [Common valueForKey:P_IMGURL dic:self.dataDic];
            [imgView setImageWithURL:[Common getFullDownloadPathByRelativePath:imgPath] placeholderImage:[Common getPlaceholderImage:ePIT_StorePhoto]];
            break;
        }
        case 1:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"StoreTitleCell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"StoreTitleCell"  owner:self options:nil] lastObject];
                cell.contentView.backgroundColor = self.tableView.backgroundColor;
                UIButton* btnLocation = (UIButton*)[cell viewWithTag:1002];
                [btnLocation setImage:[UIImage imageNamed:@"hotel/map.png"] forState:UIControlStateNormal];
            }
            [self loadStoreTitleCellData:cell];
            break;
        }
        case 2:
        {
            StoreBriefCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StoreBriefCell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[StoreBriefCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"StoreBriefCell"];
                cell.contentView.backgroundColor = self.tableView.backgroundColor;
            }
            [cell setTitle:@"简介"];
            [cell setContent:self.brief ifShowAll:self.ifShowAll];
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        case 3:
        {
            GoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodsCell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[GoodsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"GoodsCell"];
                cell.contentView.backgroundColor = self.tableView.backgroundColor;
            }
            if (indexPath.row < self.goodsList.count) {
                NSDictionary* cellData = self.goodsList[indexPath.row];
                NSString *name = [Common valueForKey:P_NAME dic:cellData];
                BOOL ifShowDetail = [self.ifGoodsShowDetail[indexPath.row] boolValue];
                NSArray *goodsDetail = [self getGoodsDetail:indexPath.row];
                
                [cell setGoodsName:name];
                [cell setGoodsDetail:goodsDetail ifShowDetail:ifShowDetail];
            }
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        default:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
            }
        }
            break;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


@end
